import {Tabs, Spin} from 'antd';
import {inject, observer} from 'mobx-react';
import {observable, action, toJS} from 'mobx';
import {WeaInputSearch, WeaNewScroll, WeaOrgTree,WeaAvatar} from 'ecCom';
import {WeaNewScrollPagination, WeaTab} from 'ecCom';
import AttentionTool from './AttentionTool';
import WeaBlogDict from '../Component/wea-blog-dict';
import WeaWhitePage from "../Component/wea-white-page";
import {routerShape} from 'react-router';

const TabPane = Tabs.TabPane;
const innerHref = WeaBlogDict.href;

import { WeaLocaleProvider } from "ecCom";
const getLabel = WeaLocaleProvider.getLabel;

@inject('blogMyAttention')
@observer
class LeftTab extends React.Component {
    static contextTypes = {
        router: routerShape
    };

    constructor(props) {
        super(props);
        this.search = this.search.bind(this);
        this.chooseUser = this.chooseUser.bind(this);
        this.changeTab = this.changeTab.bind(this);
        this.clickTree = this.clickTree.bind(this);
        this.queryNext = this.queryNext.bind(this);
        this.query = this.query.bind(this);
        this.updateUserAttentionStatus = this.updateUserAttentionStatus.bind(this);
        this.params = {
            searchUserName: "",
            currentPage: 1,
            pageSize: 30,
            type:"attention"
        };
        this.state = {
            tab: "1",
            endTip: false,
            myAttentions: []
        };
    }

    componentDidMount() {
        this.search();
        this.props.blogMyAttention.getAttentionCountInfos();
        this.props.blogMyAttention.setType("attention");
        let {router} = this.context;
        if (router) {
            router.push(innerHref.viewAttentionList());
        }
    }

    componentWillReceiveProps(nextProps) {
        // changeTab会触发一次onScroll事件，而且是在changeTab执行完之后触发的，非常诡异。
        // 这里由于endTip是一个与props无交互的状态，暂时就这么处理了。
        let {status} = this.props.blogMyAttention;
        let {myAttentions} = toJS(status);

        if (myAttentions != this.state.myAttentions) {
            this.setState({
                endTip: false
            });
        }
    }

    onSearchChange = (userName) => {
        this.setState({
            endTip: false
        });

        this.props.blogMyAttention.clearLeft();
        let ttype  = 'attention';
        let ttab = this.state.tab;
        if(ttab=='1'){
            ttype = 'attention';
        }else if(ttab == '2'){
            ttype = 'org';
        }else {
            ttype = 'share';
        }
        this.params = {
            currentPage: 1,
            searchUserName: userName || "",
            pageSize: 30,
            type:ttype
        };

        if(this.state.tab=='2'){
            this.props.blogMyAttention.setOrg(true);
        }
        this.query();
    }

    search(userName) {
        this.setState({
            endTip: false
        });
        this.props.blogMyAttention.clearLeft();
        let ttype  = 'attention';
        let ttab = this.state.tab;
        if(ttab=='1'){
            ttype = 'attention';
        }else if(ttab == '2'){
            ttype = 'org';
        }else {
            ttype = 'share';
        }
        this.params = {
            currentPage: 1,
            searchUserName: userName || "",
            pageSize: 30,
            type:ttype
        };

        if(this.state.tab=='2'){
            this.props.blogMyAttention.setOrg(true);
        }
        this.query();
    }

    queryNext() {
        let {status} = this.props.blogMyAttention;
        let {myAttLasted,myAttLoaded} = toJS(status);
        if (myAttLasted) {
            this.state.endTip || this.setState({
                endTip: true
            });
            return;
        }
        if(!myAttLoaded){
            return;
        }
        this.params.currentPage++;
        this.query();
    }

    query() {
        if (this.state.tab == '1')
        {
            this.params.type = "attention";
            this.props.blogMyAttention.getMyAttentions(this.params);
        }
        else if (this.state.tab == '3')
        {
            this.params.type = "share";
            this.props.blogMyAttention.getMyAttentionShare(this.params);
        }
        else if(this.state.tab == '2')
        {
            this.params.type = "org";
            this.props.blogMyAttention.getMyAttentionShare(this.params);
        }
    }

    updateUserAttentionStatus(attnInfo) {
        this.props.blogMyAttention.updateUserAttentionStatus(attnInfo);
    }

    chooseUser(userId) {
        this.props.blogMyAttention.chooseUser(userId);
        let {router} = this.context;
        
        let tab = this.state.tab;
        if (router) {
            router.push(innerHref.viewAttentionUserPar(userId,tab));
        }
    }

    changeTab(key) {
        let de = key;

        if(de == '2'){
            this.setState({tab: key, endTip: false});
        }else {
            this.setState({tab: key, endTip: false}, this.search);
            this.refs.search && this.refs.search.setState({
                value: ""
            });
        }

    }

    clickTab = (v) => {
        // let date = new Date();
        // let year = date.getFullYear();
        // let month = date.getMonth()+1;
        // let day = date.getDate();
        // let monthstr = month>9 ? month :"0"+month;
        // let daystr = day>9 ? day : "0"+day;
        // let currentdate = year+"-"+monthstr+"-"+daystr;
        // this.props.blogMyAttention.getAttentionWorkDateList({workDate:currentdate},0);
        if(v==1){
            this.props.blogMyAttention.getAttentionCountInfos();
            this.props.blogMyAttention.setType("attention");
            let {router} = this.context;
            if (router) {
                router.push(innerHref.viewAttentionList());
            }
        }else if(v==2 ){
            this.props.blogMyAttention.setOrg(false);
            this.props.blogMyAttention.setType("org");
        }else if(v==3 ){

            this.props.blogMyAttention.getAttentionCountInfos({type:'share'});
            this.props.blogMyAttention.setType("share");
            let {router} = this.context;
            if (router) {
                router.push(innerHref.viewAttentionList());
            }
        }


    }

    clickTree(t) {
        if (t && t.node && t.node.props && t.node.props.type == 3) {
            this.chooseUser(t.node.props.id);
        }
    }

    render() {
        let {status} = this.props.blogMyAttention;
        let {myAttentions, userId, myAttLoaded} = toJS(status);
        let list = myAttentions || [];
        let isOrgTree = (this.state.tab != "1" && this.state.tab != "3"&&!status.isOrg);
        const topTab = [
            {
                groupid: 'focus',
                title: getLabel(26469,"我的关注"),
                viewcondition: '1'
            },
            {
                groupid: 'group',
                title: getLabel(25332,"组织结构"),
                viewcondition: '2'
            },
            {
                groupid: 'share',
                title: getLabel(513653,"分享给我"),
                viewcondition: '3'
            },
        ];

        const style = {
            width: 40,
            height: 40,
            display: "inline-block",
            "vertical-align": "middle"
        };
        return (
            <div className="attentionTab" style={{width: '100%', height: '100%'}}>
                <WeaTab ecId={`${this && this.props && this.props.ecId || ''}_WeaTab@aw07qe`}
                    datas={topTab}
                    keyParam="viewcondition"
                    countParam="groupid"
                    selectedKey={this.state.tab}
                    onTabClick={v => this.clickTab(v)}
                    onChange={v => this.changeTab(v)}
                />
                {/* <Tabs defaultActiveKey="1" size="small" onChange={this.changeTab} animated={false}>
						<TabPane tab="我的关注" key="1"/>
						<TabPane tab="组织结构" key="2"/>
						<TabPane tab="分享给我" key="3"/>
					</Tabs> */}

                <div className="search">
                    <WeaInputSearch ecId={`${this && this.props && this.props.ecId || ''}_WeaInputSearch@6axu7d`} ref="search" style={{width: '100%'}} placeholder={getLabel(507615,'请输入人员姓名/首字母') } onSearch={this.search}  onSearchChange={this.onSearchChange}/>
                </div>

                {isOrgTree ||
                <WeaNewScrollPagination ecId={`${this && this.props && this.props.ecId || ''}_WeaNewScrollPagination@tn8tl2`} ref="scroll" onScrollEnd={this.queryNext}>
                    <ul className='attentionlist'>
                        {
                            list.map(l => {
                                let className = l.userId == userId ? "cur" : "";
                                return (
                                    <li key={l.userId} className={className}>
                                        <div className="line cur-pointer" onClick={this.chooseUser.bind(this, l.userId)}>
                                            <AttentionTool ecId={`${this && this.props && this.props.ecId || ''}_AttentionTool@qgo23r@${l.userId}`} isreceive={l.isreceive} attentionStatus={l.attentionStatus} userId={l.userId}
                                                           islower={l.islower}
                                                           callback={this.updateUserAttentionStatus}/>
                                            <span className="fl" style={style}>
                                                <WeaAvatar ecId={`${this && this.props && this.props.ecId || ''}_WeaAvatar@spjthp@${l.userId}`} userId={l.userId}></WeaAvatar>
                                            </span>
                                            <div className="content">
                                                <div className="dis-block">
                                                    <span className="lastName">{l.lastname}</span>
                                                    {(l.isnew == "1") && (<span className="new">•</span>)}
                                                </div>
                                                <span className="dept text-elli">{l.departmentName + ' ' + l.jobtitle}</span>
                                            </div>
                                        </div>
                                    </li>
                                )
                            })
                        }
                    </ul>
                    {myAttLoaded || <div className="pt20 align-center"><Spin ecId={`${this && this.props && this.props.ecId || ''}_Spin@9879mj`}/></div>}
                    {list.length > 0 && this.state.endTip &&
                    <div className="endTip"><i className="icon-blog-ArrowheadUp"/>{getLabel(384465,"没有其他人了")}</div>}
                    {myAttLoaded && list.length == 0 && <div className="pt20 align-center"><WeaWhitePage ecId={`${this && this.props && this.props.ecId || ''}_WeaWhitePage@v7c1iy`}/></div>}
                </WeaNewScrollPagination>
                }

                <div className="weiboOrgTree" style={{display: isOrgTree ? '' : 'none', height: '100%', paddingBottom: '40px'}}>
                    <WeaOrgTree ecId={`${this && this.props && this.props.ecId || ''}_WeaOrgTree@dz9bbd`} isLoadUser={true}
                                treeNodeClick={this.clickTree} noCache vtreeMode
                    />
                </div>
            </div>
        );
    }
}

export default LeftTab;
